# 5 模型保存与恢复
import  tensorflow as tf

import  numpy as np

from  tensorflow import  keras

from  tensorflow.keras import  layers



input_x = tf.keras.Input(72,)

hidden1 =layers.Dense(32,activation=tf.keras.activations.relu)(input_x)
hidden2 = layers.Dense(32,activation=tf.keras.activations.relu)(hidden1)
output = layers.Dense(10, activation=tf.keras.activations.softmax)(hidden2)

# 构建模型实力

model= tf.keras.Model(inputs = input_x,outputs = output)

model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
             loss=tf.keras.losses.categorical_crossentropy,
             metrics=['accuracy'])


train_x = np.random.random((1000, 72))
train_y = np.random.random((1000, 10))

val_x = np.random.random((200, 72))
val_y = np.random.random((200, 10))

# model.fit(train_x, train_y, batch_size=32, epochs=5)


callbacks = [
    tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
    tf.keras.callbacks.TensorBoard(log_dir='./logs')
]
model.fit(train_x, train_y, batch_size=16, epochs=50,
         callbacks=callbacks, validation_data=(val_x, val_y))
# 保存权重
model.save_weights('./weight/model1')
# 载入
model.load_weights('./weight/model1')
# 保存为h5 格式

model.save_weights('./model.h5', save_format='h5')
# 载入权重
model.load_weights('./model.h5')


# 序列化成json
import json
import pprint
json_str = model.to_json()
pprint.pprint(json.loads(json_str))
# 从json中重建模型
fresh_model = tf.keras.models.model_from_json(json_str)


# 保存为yaml
#  保持为yaml格式  #需要提前安装pyyaml

yaml_str = model.to_yaml()
print(yaml_str)
# 从yaml数据中重新构建模型
fresh_model = tf.keras.models.model_from_yaml(yaml_str)


# 保存整个模型

model_save = tf.keras.Sequential([
  layers.Dense(10, activation='softmax', input_shape=(72,)),
  layers.Dense(10, activation='softmax')
])
model_save.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model_save.fit(train_x, train_y, batch_size=32, epochs=5)
# 保存整个模型
model_save.save('all_model.h5')
# 导入整个模型
model_load = tf.keras.models.load_model('all_model.h5')